
cc.Class({
    extends: cc.Component,

    properties: {
        posLabel: cc.Label,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        // 坐标汇总
        this.map = [[0,0]];
        this.nowX = 0;
        this.nowY = 0;

        // 屏幕宽高
        this.canvasWidth = cc.Canvas.instance.node.width;
        this.canvasHeight = cc.Canvas.instance.node.height;

        // 背景原始宽高
        this.bgStartWidth = this.node.width;
        this.bgStartHeight = this.node.height;

        // 触摸监听
        this.node.on('touchstart', this.onTouchStart, this);
        this.node.on('touchend', this.onTouchEnd, this);   
    },

    onTouchStart (event) {
        // 获取手指初始坐标
        this.startPos = this.node.convertToNodeSpaceAR(event.getLocation());
    },

    onTouchEnd (event) {
        // 获取手指终点坐标
        let endPos = this.node.convertToNodeSpaceAR(event.getLocation());

        let disX = endPos.x - this.startPos.x;           // x方向滑动距离
        let disY = endPos.y - this.startPos.y;           // y方向滑动距离
        let triggerDis = this.canvasWidth / 20;          // 屏幕宽度的百分之几作为滑动触发宽度

        // 如果滑动距离大于等于屏幕宽度的百分之几则滑动背景
        if (disX >= triggerDis) {
            // 手指往右滑
            this.nowX -= 1;
            let isNew = this.addToMap(this.nowX, this.nowY);

            if (isNew)
                {this.node.width = this.node.width + this.bgStartWidth*2;}
        }
        else if (disX<0 && Math.abs(disX)>=triggerDis) {
            // 手指往左滑
            this.nowX += 1;
            let isNew = this.addToMap(this.nowX, this.nowY);

            if (isNew)
                {this.node.width = this.node.width + this.bgStartWidth*2;}
        }
        else if (disY >= triggerDis) {
            // 手指往上滑
            this.nowY -= 1;
            let isNew = this.addToMap(this.nowX, this.nowY);

            if (isNew)
                {this.node.height = this.node.height + this.bgStartHeight*2;}
        }
        else if (disY<0 && Math.abs(disY)>triggerDis) {
            // 手指往下滑
            this.nowY += 1;
            let isNew = this.addToMap(this.nowX, this.nowY);

            if (isNew)
                {this.node.height = this.node.height + this.bgStartHeight*2;}
        }

        // 设置文本内容
        this.posLabel.string = '(' + this.nowX + ', ' + this.nowY + ')'; 
        
        // 移动背景(子节点也会移动)
        let moveAction = cc.moveTo(0.8, cc.v2(-this.nowX*this.bgStartWidth, -this.nowY*this.bgStartHeight));
        this.node.runAction(moveAction);
    },

    addToMap (x, y) {
        // 首先循环查看是否已经存在
        for (let i=0; i<this.map.length; i++) {
            if (this.map[i][0]==x && this.map[i][1]==y) 
                {return false;}
        }

        // 如果没有则加到map中
        this.map.push([x, y]);
        return true;
    },

    restore () {
        // 还原文本和位置到(0, 0)
        this.nowX = 0;
        this.nowY = 0;
        this.posLabel.string = '(0, 0)'; 
        let moveAction = cc.moveTo(0.8, cc.v2(0, 0));
        this.node.runAction(moveAction);
    }
});
